import Axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import config from "@/config";
import { Response } from "./Model";
const {BASE_URL,SUCCESS_CODE} = config;
Axios.defaults.baseURL=BASE_URL;
// 拦截头
{
    Axios.interceptors.request.use((config:AxiosRequestConfig) =>{
        const token=sessionStorage.getItem("token");
        if(!token) return config;
        if(!config.headers) return config;
        config.headers.Authorization = `Bearer  + ${token}`;
        return config;
    },error=>{
        throw error;
    })
}


{
    Axios.interceptors.response.use((response:AxiosResponse<Response<any>>) => {
    if (response.config.responseType === 'blob') {
      // 如果是文件流，直接过
      return response;
    } else if (response.data?.code === SUCCESS_CODE) {
      return response.data?.data;
    } else {
        ElMessage.error(response.data?.msg);
        throw response.data?.msg;
    }
  },
  (error: AxiosError) => {
    ElMessage.error(error.message)
    throw error;
  }
)
}




export default Axios;